require("babel-polyfill")
const InputTool = require("./lib/InputTool");
const JszipTool = require("./lib/JszipTool");
const MAX_WIDTH = 2048;
let marge_model = 0;


let cacheCanvas = document.createElement("canvas");
let cacheCtx = cacheCanvas.getContext("2d");
cacheCanvas.width = MAX_WIDTH;
cacheCanvas.height = MAX_WIDTH;

let jszipTool = new JszipTool();



let imageContiner = document.querySelector("#imageContiner");
let margeBtn = document.querySelector("#margeBtn");
let myInputNums = document.querySelector('#myInputNums');
let inp = document.querySelector('#myInput')
let modelSelect = document.querySelector("#marge_model_select")

modelSelect.onchange = ()=>{
    marge_model = +modelSelect.value
    showModelStatus()
}
let inputTool = new InputTool(inp,myInputNums);
margeBtn.addEventListener("click",()=>{
    if(inputTool.isLoadIng()){
        inputTool.onload = (result)=>{
            result = nameSort(result)
            let images = result.map(item=>item.value);
            let name = result[0].name;
            saveToFile(cacheCtx,images,getMergeImageName(name))
        }
    } else {
        if(inputTool.result && inputTool.result.length){
            let data = nameSort(inputTool.result)
            let images = data.map(item=>item.value);
            let name = inputTool.result[0].name;
            saveToFile(cacheCtx,images,getMergeImageName(name))
        }
    }
})
inputTool.setType("image");

function drawImageToMyCanvas(){
}
function saveToFile(cacheCtx,images,name){
    cacheCtx.clearRect(0,0,cacheCanvas.width,cacheCanvas.height);
    switch(marge_model){
        case 0:
            saveToFileVH(cacheCtx,images,name)
            break;
        case 1:
            saveToFileV(cacheCtx,images,name)
            break;
        case 2:
            saveToFileH(cacheCtx,images,name)
            break;
    }
}
async function saveToFileVH(cacheCtx,images,saveName){
    let customcol = (+document.querySelector("#customcol").value || null);
    imageContiner.innerHTML = "";
    let imgNums = images.length,
    imgW = images[0].width,
    imgH = images[0].height,
    n = imgW/imgH,
    col = customcol || Math.ceil(Math.sqrt(imgNums/n)),
    row = Math.ceil(imgNums/col);
    saveName += `&&${imgNums}%${col},5,0`
    cacheCanvas.width = col * imgW;
    cacheCanvas.height = row * imgH;
    let y = 0;
    for(let i = 0;i<images.length;i++){
        let img = images[i];
        let x = i%col*imgW;
        y = Math.floor(i/col)*imgH;
        cacheCtx.drawImage(img,x,y,imgW,imgH);
    }
    drawImageToMyCanvas();
    let image = new Image();
    image.style.width = 500 + "px";
    image.style.height = 500 * cacheCanvas.height/cacheCanvas.width + "px";
    image.src = cacheCtx.canvas.toDataURL("image/png");
    imageContiner.appendChild(image);
    jszipTool.saveCanvasPngToFile(saveName,cacheCtx.canvas,".png",()=>{
        console.log("success")
        cacheCtx.clearRect(0,0,cacheCanvas.width,cacheCanvas.height);
    })
}
async function saveToFileH(cacheCtx,arr,saveName){
    imageContiner.innerHTML = "";
    let size = computeSizeH(arr.length,arr[0].width,arr[0].height)
    cacheCanvas.width = size;
    cacheCanvas.height = arr[0].height;
    let y = 0;
    for(let i = 0;i<arr.length;i++){
        let img = arr[i];
        let x = i*img.width;
        cacheCtx.drawImage(img,x,y,img.width,img.height);
    }
    drawImageToMyCanvas();
    let image = new Image();
    image.style.width = 800 + "px";
    image.style.height = 800 * cacheCanvas.height/cacheCanvas.width + "px";
    image.src = cacheCtx.canvas.toDataURL("image/png");
    imageContiner.appendChild(image);
    jszipTool.saveCanvasPngToFile(saveName,cacheCtx.canvas,".png",()=>{
        console.log("success")
        cacheCtx.clearRect(0,0,cacheCanvas.width,cacheCanvas.height);
    })
}
async function saveToFileV(cacheCtx,arr,saveName){
    imageContiner.innerHTML = "";
    cacheCanvas.width = MAX_WIDTH;
    cacheCanvas.height = MAX_WIDTH;
    let maxCol = Math.floor(MAX_WIDTH/arr[0].height);
    let maxRow = Math.floor(MAX_WIDTH/arr[0].width);
    let maxSize = maxCol*maxRow;
    for(let i = 0;i<arr.length;i++){
        let j = i%maxSize;
        let img = arr[i];
        let x = Math.floor(j/maxCol)*img.width;
        let y = j%maxCol*img.height
        if(j == 0 && (arr.length - i <= maxSize)){
            let size = computeSize(arr.length - i,img.width,img.height)
            maxCol = Math.floor(size/arr[0].height);
            maxRow = Math.floor(size/arr[0].width);
            maxSize = maxCol*maxRow;
            cacheCanvas.width = size;
            cacheCanvas.height = size;
        }
        cacheCtx.drawImage(img,x,y,img.width,img.height);
    }
        drawImageToMyCanvas();
        let image = new Image();
        image.style.width = 500 + "px";
        image.style.height = 500 * cacheCanvas.height/cacheCanvas.width + "px";
        image.src = cacheCtx.canvas.toDataURL("image/png");
        imageContiner.appendChild(image);
        jszipTool.saveCanvasPngToFile(saveName,cacheCtx.canvas,".png",()=>{
            console.log("success")
            cacheCtx.clearRect(0,0,cacheCanvas.width,cacheCanvas.height);
        })
}
function computeSize(num,width,height){
    let w = MAX_WIDTH;
    let row = Math.floor(w/height);
    let col = Math.floor(w/width);
    while(Math.ceil(num/row) <= col){
        w /= 2;
        row = Math.floor(w/height);
        col = Math.floor(w/width);
    }
    return w * 2;
}
function computeSizeH(num,width,height){
    return width*num;
}
function saveCanvasToZip(name,canvas){-3
    return new Promise((resolve)=>{
        canvas.toBlob((blob)=>{
            jszipTool.add({name:name,data:blob});
            resolve(blob);
        })
    })
}
function nameSort(arr){
    arr.sort((a,b)=>{
        return +a.name.substr(a.name.length-3) - +b.name.substr(b.name.length-3)
    })
    return arr;
}
function showModelStatus(){
    if(marge_model == 2){
        document.querySelector(".v_model").hidden = false;
        document.querySelector(".h_model").hidden = true;
        document.querySelector(".vh_model").hidden = true;
        document.querySelector("#vh_col_input").style.display = "none";
    } else if(marge_model == 1){
        document.querySelector(".v_model").hidden = true;
        document.querySelector(".h_model").hidden = false;
        document.querySelector(".vh_model").hidden = true;
        document.querySelector("#vh_col_input").style.display = "none";
    } else if(marge_model == 0){
        document.querySelector(".v_model").hidden = true;
        document.querySelector(".h_model").hidden = true;
        document.querySelector(".vh_model").hidden = false;
        document.querySelector("#vh_col_input").style.display = "flex";
    }
}
showModelStatus();